#include "DeviceEdit.h"
#include "ui_DeviceEdit.h"
#include "Tools/MyUrl.h"

#include <QPushButton>
#include <QNetworkAccessManager>
#include <QUrl>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QByteArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QVBoxLayout>

DeviceEdit::DeviceEdit(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::DeviceEdit)
{
    ui->setupUi(this);
    this->deviceSelectInit();
}

void DeviceEdit::deviceSelectInit()
{
    QVBoxLayout* layout = new QVBoxLayout(this->ui->widget_deviceSelect);
    layout->setContentsMargins(10, 10, 10, 10);
    layout->setSpacing(10);

    QNetworkAccessManager* manager = new QNetworkAccessManager();
    connect(manager, &QNetworkAccessManager::finished, this, [=](QNetworkReply* reply){
        QJsonParseError parseError;
        QJsonDocument jsonData = QJsonDocument::fromJson(reply->readAll(), &parseError);

        if (parseError.error != QJsonParseError::NoError)
        {
            qDebug() << "JSON 解析失败：" << parseError.errorString() << __LINE__ << __FILE_NAME__;
            return;
        }
        QJsonObject rootObject = jsonData.object();
        QJsonArray deviceArray = rootObject["devices"].toArray();


        for(const QJsonValue &value: deviceArray)
        {
            QJsonObject deviceJson = value.toObject();
            QPushButton* button = new QPushButton(deviceJson["device_id"].toString());
            layout->addWidget(button);
        }
    });


    QNetworkRequest* request = new QNetworkRequest(QUrl(MyUrl::deviceSelect));
    request->setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    manager->get(*request);
}

void DeviceEdit::bodyInit(DeviceInformation* info)
{

    if(info == nullptr)
    {
        this->ui->lineEdit_deviceId->clear();
        this->ui->lineEdit_connectionStatus->clear();
        this->ui->lineEdit_createTime->clear();
        this->ui->lineEdit_isEnabled->clear();
        this->ui->lineEdit_creator->clear();
        this->ui->lineEdit_username->clear();
    }
    else
    {
        this->ui->lineEdit_deviceId->setText(info->m_deviceId);
        this->ui->lineEdit_connectionStatus->setText(QString::number(info->m_connectionStatus));
        this->ui->lineEdit_createTime->setText(info->m_createTime);
        this->ui->lineEdit_isEnabled->setText(QString::number(info->m_isEnabled));
        this->ui->lineEdit_creator->setText(info->m_creator);
        this->ui->lineEdit_username->setText(info->m_username);
    }

}

DeviceEdit::~DeviceEdit()
{
    delete ui;
}

void DeviceEdit::on_pushButton_save_clicked()
{

}


void DeviceEdit::on_pushButton_cancel_clicked()
{

}

